package com.xiaobai.zhuangxiuguanjia.activities;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.xiaobai.zhuangxiuguanjia.R;
import com.xiaobai.zhuangxiuguanjia.Utils.DataCleanManager;
import com.xiaobai.zhuangxiuguanjia.Utils.GetVersion;
import com.xiaobai.zhuangxiuguanjia.Utils.PhoneCall;
import com.xiaobai.zhuangxiuguanjia.Utils.ViewHolder;
import com.xiaobai.zhuangxiuguanjia.adapters.MyGridViewAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.wechat.friends.Wechat;

public class SettingsActivity extends AppCompatActivity
        implements AdapterView.OnItemClickListener, View.OnClickListener {

    private static final int[] titles = new int[]{R.string.settings_title1, R.string.settings_title2,
            R.string.settings_title3, R.string.settings_title4, R.string.settings_title5,
            R.string.settings_title6, R.string.settings_title7, R.string.settings_title8};
    private MyAdapter adapter;
    private List<Map<String, Object>> list;
    private String cache;
    private List<Map<String, Object>> appMarketList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        String versionCode = GetVersion.getVersion(this);
        cache = DataCleanManager.getTotalCacheSize(this);

        Object[] others = new Object[]{R.mipmap.ic_jiantou, versionCode, cache};

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle("设置");

        ListView settingsList = (ListView) findViewById(R.id.settings_list);

        list = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("title", titles[i]);
            if (i == 0)
                map.put("other", null);
            else if (i == 4)
                map.put("other", others[1]);
            else if (i == 6)
                map.put("other", others[2]);
            else
                map.put("other", others[0]);

            list.add(map);
        }

        adapter = new MyAdapter(list);
        settingsList.setAdapter(adapter);

        settingsList.setOnItemClickListener(this);

        Intent intent = new Intent();
        intent.setData(Uri.parse("market://details?id=android.browser"));
        List<ResolveInfo> infos = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        Log.d("infos", String.valueOf(infos.size()));
        appMarketList = new ArrayList<>();
        for (ResolveInfo info : infos) {
            ActivityInfo activityInfo = info.activityInfo;
            CharSequence label = activityInfo.loadLabel(getPackageManager());
            Drawable icon = activityInfo.loadIcon(getPackageManager());
            Map<String, Object> map = new HashMap<>();
            map.put("pckname", activityInfo.packageName);
            map.put("classname", activityInfo.name);
            map.put("icon", icon);
            map.put("label", label);
            appMarketList.add(map);
        }

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (position) {
            case 0:
                PhoneCall.phoneCall(SettingsActivity.this);
                break;
            case 1:
                // TODO 赏个好评
                LinearLayout ll = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.app_market_grid_view_layout, null);
                GridView gridView = (GridView) ll.findViewById(R.id.app_market_grid_view);
                final Button always = (Button) ll.findViewById(R.id.app_market_always);
                final Button onlyOnce = (Button) ll.findViewById(R.id.app_market_only_once);
                always.setEnabled(false);
                onlyOnce.setEnabled(false);
                final MyGridViewAdapter adapter = new MyGridViewAdapter(this, appMarketList);
                gridView.setAdapter(adapter);
                AlertDialog.Builder adb = new AlertDialog.Builder(this);
                adb.setView(ll);
                gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        always.setEnabled(true);
                        onlyOnce.setEnabled(true);
                        adapter.setClickTemp(position);
                        adapter.notifyDataSetChanged();

                        Map<String, Object> map = appMarketList.get(position);
                        final String pckname = (String) map.get("pckname");
                        final String classname = (String) map.get("classname");

                        Log.d("pckname", pckname);
                        Log.d("classname", classname);

                        // 启动点击的应用市场软件
                        final Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_LAUNCHER);
                        ComponentName cn = new ComponentName(pckname, classname);
                        intent.setComponent(cn);

                        always.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(intent);
                                overridePendingTransition(R.anim.activity_zoom_in, 0);
                            }
                        });
                        onlyOnce.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(intent);
                                overridePendingTransition(R.anim.activity_zoom_in, 0);
                            }
                        });

                    }
                });
                adb.show();
                break;
            case 2:
                // TODO 转跳建议页面
                break;
            case 3:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                View shareView = LayoutInflater.from(this).inflate(R.layout.share_layout, null);
                Button weixin = (Button) shareView.findViewById(R.id.share_to_weixin);
                Button wxCircle = (Button) shareView.findViewById(R.id.share_to_weixin_circle);
                Button weibo = (Button) shareView.findViewById(R.id.share_to_weibo);
                weixin.setOnClickListener(this);
                wxCircle.setOnClickListener(this);
                weibo.setOnClickListener(this);
                builder.setView(shareView);
                builder.show();
                break;
            case 4:
                // TODO 检查更新
                break;
            case 5:
                startActivity(new Intent(this, ServiceDocActivity.class));
                overridePendingTransition(R.anim.activity_zoom_in, 0);
                break;
            case 6:
                list.remove(6);
                Map<String, Object> map = new HashMap<>();
                map.put("title", R.string.cleaning_cache);
                map.put("other", cache);
                list.add(6, map);
                this.adapter.notifyDataSetChanged();
                DataCleanManager.clearAllCache(this);
                Map<String, Object> map1 = new HashMap<>();
                map1.put("title", titles[6]);
                map1.put("other", "0B");
                list.remove(6);
                list.add(6, map1);
                this.adapter.notifyDataSetChanged();
                break;
            case 7:
                startActivity(new Intent(this, RecommendAppListActivity.class));
                overridePendingTransition(R.anim.activity_zoom_in, 0);
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // TODO 第三方分享
            case R.id.share_to_weixin:
                Toast.makeText(this, "分享到微信", Toast.LENGTH_SHORT).show();
                Wechat.ShareParams sp1 = new Wechat.ShareParams();
                sp1.setText("分享装修管家");
                Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
                wechat.setPlatformActionListener(new PlatformActionListener() {
                    @Override
                    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                        Toast.makeText(SettingsActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Platform platform, int i, Throwable throwable) {
                        throwable.printStackTrace();
                    }

                    @Override
                    public void onCancel(Platform platform, int i) {

                    }
                });
                wechat.share(sp1);
                break;
            case R.id.share_to_weixin_circle:
                Toast.makeText(this, "分享到微信朋友圈", Toast.LENGTH_SHORT).show();
                Wechat.ShareParams sp2 = new Wechat.ShareParams();
                sp2.setText("分享装修管家");
                Platform wexin = ShareSDK.getPlatform(Wechat.NAME);
                wexin.setPlatformActionListener(new PlatformActionListener() {
                    @Override
                    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                        Toast.makeText(SettingsActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Platform platform, int i, Throwable throwable) {
                        throwable.printStackTrace();
                    }

                    @Override
                    public void onCancel(Platform platform, int i) {

                    }
                });
                wexin.share(sp2);
                break;
            case R.id.share_to_weibo:
                Toast.makeText(this, "分享到新浪微博", Toast.LENGTH_SHORT).show();
                SinaWeibo.ShareParams sp3 = new SinaWeibo.ShareParams();
                sp3.setText("分享装修管家");
                Platform weibo = ShareSDK.getPlatform(SinaWeibo.NAME);
                weibo.setPlatformActionListener(new PlatformActionListener() {
                    @Override
                    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                        Toast.makeText(SettingsActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Platform platform, int i, Throwable throwable) {
                        throwable.printStackTrace();
                    }

                    @Override
                    public void onCancel(Platform platform, int i) {
                        // 取消
                    }
                }); // 设置分享事件回调
                // 执行图文分享
                weibo.share(sp3);
                break;
        }
    }

    private class MyAdapter extends BaseAdapter {

        private List<Map<String, Object>> list;

        public MyAdapter(List<Map<String, Object>> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            if (list != null) {
                return list.size();
            }
            return 0;
        }

        @Override
        public Object getItem(int position) {
            if (list != null) {
                return list.get(position);
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if (convertView == null)
                convertView = LayoutInflater.from(SettingsActivity.this)
                        .inflate(R.layout.settings_item_layout, parent, false);

            TextView title = ViewHolder.getView(convertView, R.id.settings_list_title);
            TextView other = ViewHolder.getView(convertView, R.id.settings_list_other);
            View viewDivider = ViewHolder.getView(convertView, R.id.settings_list_divider);

            if (position == 1 || position == 3)
                viewDivider.setVisibility(View.VISIBLE);
            else
                viewDivider.setVisibility(View.GONE);

            Map<String, Object> map = list.get(position);
            title.setText((Integer) map.get("title"));

            if (position == 0)
                other.setVisibility(View.GONE);
            else if (position == 4)
                other.setText((String) map.get("other"));
            else if (position == 6)
                other.setText((String) map.get("other"));
            else
                other.setBackgroundResource((Integer) map.get("other"));

            return convertView;
        }
    }
}
